package com.hellogood.yaohuo.client.bussiness.pandian;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hellogood.yaohuo.client.bussiness.AbstractTab;
import com.hellogood.yaohuo.client.bussiness.FormController;
import com.hellogood.yaohuo.client.common.COrgTextItemTreeClickHandler;
import com.hellogood.yaohuo.client.common.CodeRowEditorExitHandler;
import com.hellogood.yaohuo.client.common.CommonMessages;
import com.hellogood.yaohuo.client.common.GoodsSearchWindow;
import com.hellogood.yaohuo.client.common.LoginUser;
import com.hellogood.yaohuo.client.common.OrgCodeEditorExitHandler;
import com.hellogood.yaohuo.client.common.Tools;
import com.hellogood.yaohuo.client.helper.RecordHelper;
import com.hellogood.yaohuo.shared.data.Constants;
import com.hellogood.yaohuo.shared.entity.Detail;
import com.hellogood.yaohuo.shared.entity.Org;
import com.hellogood.yaohuo.shared.entity.PdDetail;
import com.hellogood.yaohuo.shared.entity.PdForm;
import com.hellogood.yaohuo.shared.services.CommonService;
import com.hellogood.yaohuo.shared.services.OrgService;
import com.hellogood.yaohuo.shared.services.PandianService;
import com.hellogood.yaohuo.shared.vo.BasicVo;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.types.EnterKeyEditAction;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.Positioning;
import com.smartgwt.client.types.RecordSummaryFunctionType;
import com.smartgwt.client.types.RowEndEditAction;
import com.smartgwt.client.types.SummaryFunctionType;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
import com.smartgwt.client.widgets.form.validator.IsIntegerValidator;
import com.smartgwt.client.widgets.grid.HeaderSpan;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.VLayout;

public class PandianFormController extends FormController {

	public PandianFormController(AbstractTab tab) {
		super(tab);
	}

	public void initView() {
		codeItem = new TextItem("code", "单据号");
		codeItem.setCanEdit(false);
		codeItem.setValue("*");
		pszxItem = new SelectItem("pszx", "配送中心");
		pszxItem.setCanEdit(false);
		orgItem = new TextItem("org", "组织");
		orgItem.setRequired(true);
		orgItem.setCanEdit(false);
		orgItem.setDisabled(true);
		dateItem = new DateItem("date", "日期");
		dateItem.setDateFormatter(DateDisplayFormat.TOJAPANSHORTDATE);
		dateItem.setUseTextField(true);
		dateItem.setCanEdit(false);
		zdUserItem = new TextItem("zdUser", "制单人");
		zdUserItem.setCanEdit(false);
		remarkItem = new TextItem("reamrk", "备注");
		remarkItem.addKeyPressHandler(new KeyPressHandler() {

			@Override
			public void onKeyPress(KeyPressEvent event) {
				if (event.getKeyName().equals("Enter")) {
					if (form.validate()) {
						listGrid.startEditing(0, 1, false);
					}
				}
			}
		});

		orgItem.addKeyPressHandler(new COrgTextItemTreeClickHandler(orgItem, remarkItem));

		form = new DynamicForm();
		form.setSize("100%", "10%");
		form.setAlign(Alignment.CENTER);
		form.setNumCols(6);
		form.setFields(codeItem, orgItem, dateItem, zdUserItem, remarkItem);
		form.setAutoFocus(true);

		IsIntegerValidator isIntegerValidator = new IsIntegerValidator();

		ListGridField codeField = new ListGridField("pluCode", "编码");
		codeField.setWidth("7%");
		ListGridField barCodeField = new ListGridField("barCode", "条码");
		barCodeField.setWidth("10%");
		barCodeField.setCanEdit(false);
		ListGridField pmField = new ListGridField("pluName", "品名");
		pmField.setWidth("15%");
		pmField.setCanEdit(false);
		ListGridField deptField = new ListGridField("dept", "部门");
		deptField.setWidth("8%");
		deptField.setCanEdit(false);
		ListGridField typeField = new ListGridField("type", "品类");
		typeField.setWidth("8%");
		typeField.setCanEdit(false);
		ListGridField unitField = new ListGridField("unit", "单位");
		unitField.setWidth("5%");
		unitField.setCanEdit(false);
		ListGridField cupField = new ListGridField("cup", "杯级");
		cupField.setWidth("5%");
		cupField.setHidden(true);
		colorField.setWidth("5%");
		ListGridField size1Field = new ListGridField("size1", "S/58");
		size1Field.setWidth("5%");
		size1Field.setValidators(isIntegerValidator);
		size1Field.setAlign(Alignment.CENTER);
		size1Field.setValidateOnChange(true);
		ListGridField size2Field = new ListGridField("size2", "M/64");
		size2Field.setWidth("5%");
		size2Field.setValidators(isIntegerValidator);
		size2Field.setAlign(Alignment.CENTER);
		size2Field.setValidateOnChange(true);
		ListGridField size3Field = new ListGridField("size3", "L/70");
		size3Field.setWidth("5%");
		size3Field.setValidators(isIntegerValidator);
		size3Field.setAlign(Alignment.CENTER);
		size3Field.setValidateOnChange(true);
		ListGridField size4Field = new ListGridField("size4", "XL/76");
		size4Field.setWidth("5%");
		size4Field.setValidators(isIntegerValidator);
		size4Field.setAlign(Alignment.CENTER);
		size4Field.setValidateOnChange(true);
		ListGridField size5Field = new ListGridField("size5", "XXL/82");
		size5Field.setWidth("5%");
		size5Field.setValidators(isIntegerValidator);
		size5Field.setAlign(Alignment.CENTER);
		size5Field.setValidateOnChange(true);
		ListGridField size6Field = new ListGridField("size6", "XXXL/88");
		size6Field.setWidth("5%");
		size6Field.setValidators(isIntegerValidator);
		size6Field.setAlign(Alignment.CENTER);
		size6Field.setValidateOnChange(true);
		ListGridField sizeField = new ListGridField("size", "均码");
		sizeField.setWidth("5%");
		sizeField.setValidators(isIntegerValidator);
		sizeField.setValidateOnChange(true);
		ListGridField amountField = new ListGridField("amount", "数量");
		amountField.setAlign(Alignment.RIGHT);
		amountField.setWidth("7%");
		amountField.setCanEdit(false);
		amountField.setSummaryFunction(SummaryFunctionType.SUM);
		amountField.setShowGridSummary(true);
		amountField.setRecordSummaryFunction(RecordSummaryFunctionType.MULTIPLIER);

		ListGridField remarkField = new ListGridField("remark", "备注");
		remarkField.setWidth("10%");
		ListGridField[] fields = new ListGridField[] { codeField, barCodeField, pmField, deptField, typeField, unitField, cupField, colorField, size1Field, size2Field, size3Field, size4Field,
				size5Field, size6Field, sizeField, amountField, remarkField };
		listGrid = new ListGrid() {
			protected String getCellCSSText(ListGridRecord record, int rowNum, int colNum) {
				if (colNum == 1 || (colNum > 6 && colNum < 15) || colNum == 16) {
					return "background-color:#87CEEB";
				}
				return "background-color:#FFFFFF";
			};
		};

		listGrid.setFields(fields);
		listGrid.setHeaderHeight(40);
		listGrid.setSize("150%", "100%");
		listGrid.setDisabled(true);
		listGrid.setCanEdit(true);
		listGrid.setSelectOnEdit(true);
		listGrid.setShowRowNumbers(true);
		listGrid.setShowGridSummary(true);
		listGrid.setEnterKeyEditAction(EnterKeyEditAction.NEXTCELL);
		listGrid.setListEndEditAction(RowEndEditAction.NEXT);
		listGrid.setHeaderSpans(new HeaderSpan("70", new String[] { "size1" }), new HeaderSpan("75", new String[] { "size2" }), new HeaderSpan("80", new String[] { "size3" }), new HeaderSpan("85",
				new String[] { "size4" }), new HeaderSpan("90", new String[] { "size5" }), new HeaderSpan("95", new String[] { "size6" }));

		Label titleLabel = new Label();
		titleLabel.setWidth("100%");
		titleLabel.setHeight(40);
		titleLabel.setAlign(Alignment.CENTER);
		titleLabel.setContents("<H2>盘点单</H2>");

		VLayout gridLayout = new VLayout();
		gridLayout.setOverflow(Overflow.SCROLL);
		gridLayout.setSize("100%", "90%");
		gridLayout.addMember(listGrid);

		layout = new VLayout();
		layout.setSize("100%", "100%");
		layout.setMembers(titleLabel, form, gridLayout);
		buildFormPrintView();
	}

	public void bankForm() {
		Object code = codeItem.getValue();
		if (code != null) {
			List<String> list = new ArrayList<String>();
			list.add(code.toString());
			PandianService.Util.getInstance().bankForm(list, new AsyncCallback<String>() {

				@Override
				public void onSuccess(String result) {
					if (!result.equals("")) {
						SC.say(result);
					} else {
						SC.say(CommonMessages.BankSuccess);
						tab.showRzSuccessful();
						status = Constants.FORM_STATUS_BANKED;
					}
				}

				@Override
				public void onFailure(Throwable caught) {
					SC.say(caught.getMessage());
				}
			});
		}
	}

	public void saveForm() {
		if (form.validate()) {
			listGrid.saveAllEdits();
			listGrid.cancelEditing();
			Record[] rds = listGrid.getRecords();
			boolean isComplete = RecordHelper.isRecordCompleted(rds);
			if (isComplete) {
				boolean isModify = false;
				Object billNo = codeItem.getValue();
				if (billNo != null && !billNo.equals("*")) {
					isModify = true;
				}
				msgWindow = new Window();
				msgWindow.setIsModal(true);
				msgWindow.show();
				msgWindow.setWidth(200);
				msgWindow.setHeight(100);
				msgWindow.centerInPage();
				msgWindow.setTitle("提示");
				Label label = new Label();
				label.setWidth(150);
				label.setContents("  正在保存单据，请稍后...");
				label.setAlign(Alignment.CENTER);
				msgWindow.addChild(label);
				if (!isModify) {
					String orgCode = orgItem.getValue().toString().split("-")[0];
					PandianService.Util.getInstance().getLastPdBillNo(orgCode, new SaveAsyncCallback(billNo, isModify));
				} else {
					String saveResult = save(billNo.toString(), isModify);
					if (!saveResult.equals("")) {
						SC.say(saveResult);
					}
				}
			} else {
				SC.say("数据不完整，请检查。");
			}
		}
	}

	private class SaveAsyncCallback implements AsyncCallback<String> {
		boolean isModify = false;

		public SaveAsyncCallback(Object billNo, boolean isModify) {
			this.isModify = isModify;
		}

		@Override
		public void onFailure(Throwable caught) {
			msgWindow.destroy();
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(String result) {
			String saveResult = save(result.toString(), isModify);
			if (!saveResult.equals("")) {
				SC.say(saveResult);
			}
		}
	}

	public String doSave(String billNo, boolean isModify) {
		PdForm form = new PdForm();
		form.setBillNo(billNo);
		form.setBillDate(dateItem.getValue().toString());
		form.setOrgCode(orgItem.getValue() == null ? "" : orgItem.getValue().toString().split("-")[0]);
		form.setOrgName(orgItem.getValue() == null ? "" : orgItem.getValue().toString().split("-")[1]);
		form.setRemark(remarkItem.getValue() == null ? "" : remarkItem.getValue().toString());
		form.setRzDate("");
		form.setStaffCode(zdUserItem.getValue().toString().split("-")[0]);
		form.setTimeMark(Tools.getTodayFormattedDate());
		form.setStaffName(zdUserItem.getValue().toString().split("-")[1]);
		form.setNetCost(new BigDecimal(0));

		List<Detail> list = new ArrayList<Detail>();
		Record[] rds = listGrid.getRecords();
		if (rds.length > 0) {
			String pluCodeContains = "";
			LinkedHashSet<String> set = new LinkedHashSet<String>();
			int totalFormCount = 0;
			String orgCode = form.getOrgCode();
			for (int i = 0; i < rds.length; i++) {
				Record r = rds[i];
				if (r.getAttribute("barCode") == null || r.getAttribute("barCode").equals("") || r.getAttribute("amount") == null || r.getAttribute("amount").equals("")
						|| r.getAttribute("amount").equals("0")) {
					continue;
				}
				String key = r.getAttribute("pluCode") + "-" + r.getAttribute("color");
				if (set.contains(key)) {
					pluCodeContains = r.getAttribute("pluCode");
					break;
				} else {
					set.add(key);
				}
				PdDetail d = new PdDetail();
				d.setBillNo(billNo);
				d.setOrgCode(orgCode);
				d.setRzDate("");
				d.setjPrice(new BigDecimal(0));
				d.setNetPrice(new BigDecimal(0));
				d.setPrice(new BigDecimal(0));
				d.setTimeMark(Tools.getTodayFormattedDate());
				d.setBra("C");
				d.setPluCode(r.getAttribute("pluCode"));
				d.setBarCode(r.getAttribute("barCode"));
				d.setPluName(r.getAttribute("pluName"));
				d.setDepCode(r.getAttribute("dept") == null ? "" : r.getAttribute("dept").split("-")[0]);
				d.setDepName(r.getAttribute("dept") == null ? "" : r.getAttribute("dept").split("-")[1]);
				d.setColor(r.getAttribute("color").split("-")[0]);
				d.setRemark(r.getAttribute("remark") == null ? "" : r.getAttribute("remark").trim());
				d.setSize_s(r.getAttribute("size1") == null ? 0 : r.getAttributeAsInt("size1"));
				d.setSize_m(r.getAttribute("size2") == null ? 0 : r.getAttributeAsInt("size2"));
				d.setSize_l(r.getAttribute("size3") == null ? 0 : r.getAttributeAsInt("size3"));
				d.setSize_xl(r.getAttribute("size4") == null ? 0 : r.getAttributeAsInt("size4"));
				d.setSize_xxl(r.getAttribute("size5") == null ? 0 : r.getAttributeAsInt("size5"));
				d.setSize_xxxl(r.getAttribute("size6") == null ? 0 : r.getAttributeAsInt("size6"));
				d.setSize_avg(r.getAttribute("size") == null ? 0 : r.getAttributeAsInt("size"));
				int totalCount = d.getSize_avg() + d.getSize_s() + d.getSize_m() + d.getSize_l() + d.getSize_xl() + d.getSize_xxl() + d.getSize_xxxl();
				if (d.getPluCode() == null || d.getPluCode().trim().equals("") || totalCount == 0) {
					return CommonMessages.DataIsNotCompleted;
				}
				totalFormCount += totalCount;
				d.setCounts(totalCount);
				list.add(d);
			}
			if (pluCodeContains.equals("")) {
				form.setCounts(totalFormCount);
				form.setList(list);

				PandianService.Util.getInstance().saveForm(form, isModify, new SaveResultAsyncCallback(form.getBillNo()));
			} else {
				if (msgWindow != null) {
					msgWindow.destroy();
				}
				SC.say("编码为：" + pluCodeContains + " 的商品在不同的行录入了相同的颜色");
			}
		}
		return "";
	}

	public void initForm() {
		codeItem.setValue("*");
		codeItem.setDisabled(true);
		orgItem.setDisabled(true);
		dateItem.setDisabled(true);
		zdUserItem.setDisabled(true);

		OrgService.Util.getInstance().getOrgByCode(Constants.C001, new AsyncCallback<Org>() {

			@Override
			public void onSuccess(Org result) {
				if (result != null) {
					orgItem.setValue(result.getOrgCode() + "-" + result.getOrgName());
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				SC.say(caught.getMessage());
			}
		});
		remarkItem.setDisabled(false);
		remarkItem.focusInItem();
		Date date = new Date();
		dateItem.setValue(date);
		zdUserItem.setValue(LoginUser.getInstance().getCurrentUser().getStaffCode() + "-" + LoginUser.getInstance().getCurrentUser().getStaffName());

		listGrid.setData(new Record[0]);
		status = Constants.FORM_STATUS_NEW;
		listGrid.addEditorExitHandler(new OrgCodeEditorExitHandler(listGrid, this));
		listGrid.addRowEditorExitHandler(new CodeRowEditorExitHandler(listGrid));
	}

	private class SaveResultAsyncCallback implements AsyncCallback<String> {
		private String billNo = null;

		public SaveResultAsyncCallback(String billNo) {
			this.billNo = billNo;
		}

		@Override
		public void onFailure(Throwable caught) {
			msgWindow.destroy();
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(String result) {
			msgWindow.destroy();
			if (!result.equals("")) {
				SC.say(result);
			} else {
				SC.say(CommonMessages.SaveSuccess);
				codeItem.setValue(billNo);
				orgItem.setCanEdit(false);
				remarkItem.setCanEdit(false);
				listGrid.setDisabled(true);
				tab.showSaveSuccessful();
				status = Constants.FORM_STATUS_SAVED;
			}

		}
	}

	private class BasicAsyncCallback implements AsyncCallback<BasicVo> {

		private int row = -1;

		public BasicAsyncCallback(int selectedRow) {
			this.row = selectedRow;
		}

		@Override
		public void onFailure(Throwable caught) {
			SC.say(caught.getMessage());
		}

		@Override
		public void onSuccess(BasicVo result) {
			if (row >= 0) {
				if (result != null) {
					listGrid.setEditValue(row, "pluCode", result.getPluCode());
					listGrid.setEditValue(row, "barCode", result.getBarCode());
					listGrid.setEditValue(row, "pluName", result.getPluName());
					listGrid.setEditValue(row, "dept", result.getDepCode() + "-" + result.getDepName());
					listGrid.setEditValue(row, "type", result.getClsCode() + "-" + result.getClsName());
					listGrid.setEditValue(row, "unit", result.getUnit());
					if (listGrid.getEditedCell(row, "color") == null || listGrid.getEditedCell(row, "color").equals("")) {
						listGrid.setEditValue(row, "color", "0-均色");
					}
					if (listGrid.getEditedCell(row, "size1") == null || listGrid.getEditedCell(row, "size1").equals("")) {
						listGrid.setEditValue(row, "size1", "0");
					}
					if (listGrid.getEditedCell(row, "size2") == null || listGrid.getEditedCell(row, "size2").equals("")) {
						listGrid.setEditValue(row, "size2", "0");
					}
					if (listGrid.getEditedCell(row, "size3") == null || listGrid.getEditedCell(row, "size3").equals("")) {
						listGrid.setEditValue(row, "size3", "0");
					}
					if (listGrid.getEditedCell(row, "size4") == null || listGrid.getEditedCell(row, "size4").equals("")) {
						listGrid.setEditValue(row, "size4", "0");
					}
					if (listGrid.getEditedCell(row, "size5") == null || listGrid.getEditedCell(row, "size5").equals("")) {
						listGrid.setEditValue(row, "size5", "0");
					}
					if (listGrid.getEditedCell(row, "size6") == null || listGrid.getEditedCell(row, "size6").equals("")) {
						listGrid.setEditValue(row, "size6", "0");
					}
					if (listGrid.getEditedCell(row, "size") == null || listGrid.getEditedCell(row, "size").equals("")) {
						listGrid.setEditValue(row, "size", "0");
					}
				} else {
					Object code = listGrid.getEditValue(row, 1);
					if (code == null) {
						code = listGrid.getEditedCell(row, 1);
					}
					if (code != null && canBeSave) {
						if (!GoodsSearchWindow.isOpen) {
							GoodsSearchWindow window = new GoodsSearchWindow(PandianFormController.this, listGrid, code.toString());
							window.setPosition(Positioning.RELATIVE);
							window.setIsModal(true);
							window.setSize("500", "500");
							window.show();
							window.centerInPage();
							window.getListGrid().focus();
							if (code.toString().equals("")) {
								window.getKeyItem().focusInItem();
							}
						}
					}
					canBeSave = true;
				}
			} else {
				/*
				 * Record r = listGrid.getSelectedRecord(); if (result != null
				 * && r != null) { r.setAttribute("pluCode",
				 * result.getPluCode()); r.setAttribute("barCode",
				 * result.getBarCode()); r.setAttribute("pluName",
				 * result.getPluName()); r.setAttribute("dept",
				 * result.getDepCode() + "-" + result.getDepName());
				 * r.setAttribute("type", result.getClsCode() + "-" +
				 * result.getClsName()); r.setAttribute("unit",
				 * result.getUnit()); r.setAttribute("cup", "无");
				 * r.setAttribute("color", "0"); } else { SC.say("无此条码或编码"); }
				 */
			}
		}
	}

	@Override
	public void fillRowWithBasicVo() {
		col = listGrid.getEditCol();
		row = listGrid.getEditRow();

		if (col == 1) {
			Object obj = listGrid.getEditValue(row, col);
			if (obj == null) {
				obj = listGrid.getEditedCell(row, col);
			}

			Object org = orgItem.getValue();
			if (org == null) {
				SC.say(CommonMessages.InputOrgPlease);
				orgItem.setSelectOnFocus(true);
				orgItem.selectValue();
				form.focusInItem("org");
			} else if (obj != null) {
				CommonService.Util.getInstance().getBasicVoByCodeAndOrgCode(obj.toString(), org.toString(), new BasicAsyncCallback(row));
			}
		} else if (col > 7 && col < 15) {
			int amount = 0;
			for (int i = 8; i < 15; i++) {
				Object obj = listGrid.getEditValue(row, i);
				if (obj == null) {
					obj = listGrid.getEditedCell(row, i);
				}
				amount += Tools.toInteger(obj);
			}
			listGrid.setEditValue(row, 15, amount);
		}
	}

	@Override
	public void delete(String billNo) {
		PandianService.Util.getInstance().deleteForm(billNo, new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				SC.say(caught.getMessage());
			}

			@Override
			public void onSuccess(String result) {
				if (!result.equals("")) {
					SC.say(result);
				} else {
					listGrid.setData(new Record[0]);
					FormItem[] items = form.getFields();
					if (items != null) {
						for (FormItem item : items) {
							item.setCanEdit(false);
							item.setValue("");
						}
					}
					tab.showRzSuccessful();
					SC.say(CommonMessages.DeleteSuccess);
				}
			}

		});

	}

	@Override
	public VLayout buildFormPrintView() {
		printListGrid = new ListGrid();

		// listGrid.setHeaderHeight(40);
		// listGrid.setDisabled(true);
		printListGrid.setCanEdit(true);
		// listGrid.setSelectOnEdit(true);
		printListGrid.setShowRowNumbers(true);
		// Record[] rds = this.getListGrid().get.getRecords();
		// RecordList rl = this.getListGrid().
		// listGrid.setData(rds);

		Label titleLabel = new Label();
		titleLabel.setWidth("100%");
		titleLabel.setAlign(Alignment.CENTER);
		titleLabel.setContents("<H2>盘点单</H2>");

		printLayout = new VLayout();
		printLayout.setMembers(titleLabel, printForm, printListGrid);

		return printLayout;

	}
}
